from typing import Optional
from common.geoimage.raster_dataset import RasterDataset

from .raster import (
    retrieve_by_item,
    retrieve_by_uid,
    retrieve_by_items,
    retrieve_by_uids,
)

from .raster import retrieve_by_query as retrieve_by_query_paii
from .raster_remote_service import (
    retrieve_by_query as retrieve_by_query_remote,
    SUPPORTED_REMOTE_COLLECTIONS,
)


def retrieve_by_query(
    collection_id: str,
    **kwargs,
) -> Optional[RasterDataset]:
    """Retrieve data of interest from a collection id and optionally query terms.
    The function delegate to `catalog.raster.raster` for collections hosted by PAII,
    or to `catalog.raster.raster_remote_service` for collections hosted by remote services.

    Parameters
    ----------
    collection_id : str
        Data collection id for the data of interest, e.g "COPERNICUS/SENTINEL2/L2A" (a collection hosted by PAII)
        or "GOOGLEMAPS/SATELLITE" (a remote service).
    **kwargs
        More query terms or parameters controlling data retrieving process, including:

        - `spatial`: Spatial query as a `Geom` object that intersects with items of interest.
        - `temporal`: A list of datetime objects that intersects with items of interest.
        - `properties`: A dictionary of properties that matches items of interest.

        - `dest_srs`: Destination spatial reference system represented by an EPSG string,
            e.g. "EPSG:4326", "EPSG:4857", etc.
        - `dest_res`: Destination spatial resolution.
        - `resample_alg`: Algorithm for resampling, if resampling is needed, by default "near".

        - `asset_names`: A list of asset names to be retrieved from matched items.
        - `composite_strategy`: strategy used to composite multiple items during retrieving.
        - `create_db_conn`: Whether to create a database connection for the data retrieving process.

        - `fpath_dest`: File path to the retrieved raster, by default None so not to save a raster file
            but return the raster as a `RasterDataset` object.

        Please refer to the actual functions called for more details about those supported kwargs.

    Returns
    -------
    Optional[RasterDataset]
        A `RasterDataset` object for the data retrieved,
        or `None` the specified item could not be found in our catalog,
        or `None` when a result raster file of geotiff or jpeg2000 format is requested to saved.
    """
    if collection_id in SUPPORTED_REMOTE_COLLECTIONS:
        return retrieve_by_query_remote(collection_id, **kwargs)
    else:
        return retrieve_by_query_paii(collection_id, **kwargs)


__all__ = [
    retrieve_by_item,
    retrieve_by_uid,
    retrieve_by_items,
    retrieve_by_uids,
    retrieve_by_query,
]
